"""
数据模型定义
包含用户信息和订单信息的数据结构
"""

import json
from typing import List, Dict, Any


class Order:
    """订单类"""
    def __init__(self, order_id, order_type, order_amount, order_date, order_status="未付款"):
        self.order_id = order_id        # 订单号
        self.order_type = order_type    # 订单类型
        self.order_amount = order_amount # 订单金额
        self.order_date = order_date    # 订单时间
        self.order_status = order_status # 订单状态
    
    def __str__(self):
        return (
            f"订单ID: {self.order_id}   商品: {self.order_type}   订单金额: {self.order_amount}   "
            f"订单日期: {self.order_date}   订单状态: {self.order_status}"
        )

    def to_dict(self) -> Dict[str, Any]:
        """将订单对象序列化为字典"""
        return self.__dict__

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Order':
        """从字典反序列化为订单对象"""
        return cls(**data)


def create_default_hardware_orders() -> List[Order]:
    """生成系统启动时可用的硬件类订单（仅保存在内存中）"""
    return [
        Order("HW-CPU-001", "Intel Core i9-14900K", 4699, "2025-02-01", "已付款"),
        Order("HW-GPU-002", "NVIDIA RTX 4090", 12999, "2025-02-03", "已付款"),
        Order("HW-LAP-003", "MacBook Pro 16 M3 Max", 23999, "2025-02-05", "待付款"),
        Order("HW-PHN-004", "Huawei Mate 60 Pro+", 8999, "2025-02-06", "待付款")
    ]


class Vars:
    """用户环境变量类"""
    def __init__(self, user_name, user_pwd, order_list=None, current_state=None):
        self.user_name = user_name
        self.user_pwd = user_pwd
        self.order_list = order_list if order_list is not None else []
        self.current_state = current_state if current_state is not None else "IDLE"
        # 投诉相关的上下文
        self.last_complaint_category = None  # 'technical' 或 'service'
        self.manual_transfer = False         # 是否请求转人工

    def add_order(self, order):
        """添加订单"""
        self.order_list.append(order)
    
    def get_order_list(self):
        """获取订单列表"""
        return self.order_list
    
    def get_state(self):
        """获取当前状态"""
        return self.current_state

    def set_state(self, state):
        """设置当前状态"""
        self.current_state = state

    def get_user_name(self):
        """获取用户名"""
        return self.user_name
    
    def get_password(self):
        """获取密码"""
        return self.user_pwd

    def set_complaint_category(self, category: str):
        self.last_complaint_category = category

    def get_complaint_category(self):
        return self.last_complaint_category

    def set_manual_transfer(self, flag: bool):
        self.manual_transfer = bool(flag)

    def get_manual_transfer(self) -> bool:
        return self.manual_transfer

    def find_order_by_id(self, order_id):
        """根据订单ID查找订单"""
        for order in self.order_list:
            if order.order_id == order_id:
                return order
        return None

    def remove_order(self, order_id):
        """删除订单"""
        self.order_list = [order for order in self.order_list if order.order_id != order_id]

    def to_dict(self) -> Dict[str, Any]:
        """将Vars对象序列化为字典"""
        return {
            'user_name': self.user_name,
            'user_pwd': self.user_pwd,
            'order_list': [order.to_dict() for order in self.order_list],
            'current_state': self.current_state,
            'last_complaint_category': self.last_complaint_category,
            'manual_transfer': self.manual_transfer
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Vars':
        """从字典反序列化为Vars对象"""
        orders = [Order.from_dict(o) for o in data.get('order_list', [])]
        instance = cls(data['user_name'], data['user_pwd'], orders, data.get('current_state'))
        instance.last_complaint_category = data.get('last_complaint_category')
        instance.manual_transfer = data.get('manual_transfer', False)
        return instance


class UserSession:
    """用户会话管理类"""
    def __init__(self):
        self.sessions: Dict[str, Vars] = {}  # 存储用户会话信息
    
    def create_session(self, user_name, user_pwd):
        """创建用户会话"""
        user_vars = Vars(user_name, user_pwd)
        self.sessions[user_name] = user_vars
        return user_vars
    
    def get_session(self, user_name):
        """获取用户会话"""
        return self.sessions.get(user_name)
    
    def update_session(self, user_name, user_vars):
        """更新用户会话"""
        self.sessions[user_name] = user_vars
    
    def delete_session(self, user_name):
        """删除用户会话"""
        if user_name in self.sessions:
            del self.sessions[user_name]

    def save_to_file(self, filepath: str):
        """将会话数据保存到JSON文件"""
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                serializable_sessions = {uname: uvars.to_dict() for uname, uvars in self.sessions.items()}
                json.dump(serializable_sessions, f, ensure_ascii=False, indent=4)
        except IOError as e:
            print(f"Error saving sessions to {filepath}: {e}")

    def load_from_file(self, filepath: str):
        """从JSON文件加载会话数据"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                loaded_sessions = json.load(f)
                self.sessions = {uname: Vars.from_dict(data) for uname, data in loaded_sessions.items()}
        except (IOError, json.JSONDecodeError):
            # 文件不存在或格式错误，不加载
            self.sessions = {}
